from django.utils import timezone  # django转换UTC时间为本地时间
from kubernetes import client
from kubernetes.client.rest import ApiException


class ProductionOprationServiceApi():
    '''操作服务'''

    def __init__(self, namespace, service_name=None):
        self.namespace = namespace
        self.service_name = service_name
        from kubernetes import config
        config.load_kube_config(config_file="./kube_conf/product.conf")
        self.coreApi_v1 = client.CoreV1Api()
        self.extensions_v1beta1 = client.ExtensionsV1beta1Api()

    def get_service_api(self):
        '''获取对应命名空间的service'''

        try:
            service_res = self.coreApi_v1.list_namespaced_service(namespace=self.namespace, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'service列表获取失败,{e}'}
        else:
            results = []
            for service_obj in service_res.items:
                service = {}
                service['name'] = service_obj.metadata.name
                service['type'] = service_obj.spec.type
                service['create_time'] = timezone.localtime(service_obj.metadata.creation_timestamp).strftime(
                    "%Y-%m-%d %H:%M:%S")
                service['cluster_ip'] = service_obj.spec.cluster_ip
                service[
                    'internal_endpoint'] = f"{service_obj.metadata.name}:{service_obj.spec.ports[0].target_port}/{service_obj.spec.ports[0].protocol}"
                if service_obj.status.load_balancer.ingress is not None:
                    service['external_endpoint'] = service_obj.status.load_balancer.ingress
                else:
                    service['external_endpoint'] = '---'
                results.append(service)
            return results

    def get_service_name_api(self):
        '''获取对应namespace的service列表'''

        try:
            service_res = self.coreApi_v1.list_namespaced_service(namespace=self.namespace, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'service列表获取失败,{e}'}
        else:
            # 此处仅获取service名称
            results = [service.metadata.name for service in service_res.items]
            return results

    def delete_service_api(self):
        '''删除指定service'''

        try:
            Body = client.V1DeleteOptions()
            service_res = self.coreApi_v1.delete_namespaced_service(namespace=self.namespace, name=self.service_name,
                                                                    body=Body, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'service {self.service_name} 删除失败，{str(e)}'}
        else:
            print(service_res.status)
            return {'msg': f'service {self.service_name} 删除成功!'}

    def create_service_api(self, port):
        '''创建service'''

        # 定义spec
        spec = client.V1ServiceSpec(
            # 此处target_port为Pod的port
            ports=[client.V1ServicePort(name='application', port=int(port), target_port=int(port), protocol="TCP")],
            session_affinity="None",
            type="ClusterIP",
            selector={"name": self.service_name}
        )
        # 定义服务
        serviced = client.V1Service(
            api_version='v1',
            kind="Service",
            metadata=client.V1ObjectMeta(name=self.service_name, namespace=self.namespace,
                                         labels={'name': self.service_name}),
            spec=spec
        )
        # 执行创建
        try:
            self.coreApi_v1.create_namespaced_service(namespace=self.namespace, body=serviced, async_req=True).get()
        except ApiException as e:
            return {'code': 500, 'msg': f'serivce {self.service_name} 创建失败，{str(e)}'}
        else:
            return {'msg': f'service {self.service_name} 创建成功!'}
